package com.group.voting_system.utils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: xyf
 * @Date: 2019/4/19 22:37
 */
public class QRUtil {
    //二维码颜色为黑色
    private static final int BLACK = 0xFF000000;
    //二维码颜色为白色
    private static final int WHITE = 0xFFFFFFFF;
    //二维码图片格式
    private static final List<String> IMAGE_TYPE = new ArrayList<>();

    static {
        IMAGE_TYPE.add("jpg");
        IMAGE_TYPE.add("png");
    }

    /**
     * 生成二维码
     * @param codeName  二维码文件名
     * @param content   生成内容
     * @param path      生成二维码的存放位置
     * @param size      二维码的尺寸
     * @param logoPath  logo的存放位置
     * @return          返回成功与否
     */
    public static boolean createCode(String codeName, String content, String path, Integer size, String logoPath){

        String imgType = "jpg";
        BufferedImage image = getBufferedImage(content, size, logoPath);
        //生成二维码存放文件
        File file = new File(path + codeName + ".jpg");
        if (!file.exists())
            file.mkdirs();
        try {
            ImageIO.write(image, imgType, file);
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public static BufferedImage getBufferedImage(String content, Integer size, String logoPath){
        if (size == null || size <= 0)
            size = 250;
        BufferedImage image = null;
        try {

            //设置编码字符集
            Map<EncodeHintType, Object> hints = new HashMap<>();
            //设置编码
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
            //设置容错率
            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
            hints.put(EncodeHintType.MARGIN, 1);
            //1.生成二维码
            MultiFormatWriter writer = new MultiFormatWriter();
            BitMatrix matrix = writer.encode(content, BarcodeFormat.QR_CODE, size, size, hints);

            //2.获取二维码宽高
            int codeWidth  = matrix.getWidth();
            int codeHeight = matrix.getHeight();

            //3.将二维码放入缓存中
            image = new BufferedImage(codeWidth, codeHeight, BufferedImage.TYPE_INT_RGB);
            for (int i = 0; i < codeWidth; i++){
                for (int j = 0; j < codeHeight; j++){
                    //4.循环将二维码进行填补
                    image.setRGB(i, j, matrix.get(i, j) ? BLACK : WHITE);
                }
            }
            //判断是否要写入logo
            if (logoPath != null && !logoPath.equals("")){
                //从文件中获取logo
                //File类只是对logo的简单封装，可以获取到该地址的一些基本信息，还没有放入缓存中
                File logoPic = new File(logoPath);
                if (logoPic.exists()){
                    Graphics2D graphics2D = image.createGraphics();
                    //放入缓存中
                    BufferedImage logo = ImageIO.read(logoPic);
                    int widthLogo = logo.getWidth(null) > image.getWidth() * 2 / 10 ? (image.getWidth() * 2 / 10) : logo.getWidth(null);
                    int heightLogo = logo.getHeight(null) > image.getHeight() * 2 / 10 ? (image.getHeight() * 2 / 10) : logo.getHeight(null);
                    int x = (image.getWidth() - widthLogo) / 2;
                    int y = (image.getHeight() - heightLogo) / 2;
                    // 开始绘制图片
                    graphics2D.drawImage(logo, x, y, widthLogo, heightLogo, null);
                    graphics2D.drawRoundRect(x, y, widthLogo, heightLogo, 15, 15);
                    //边框宽度
                    graphics2D.setStroke(new BasicStroke(2));
                    //边框颜色
                    graphics2D.setColor(Color.WHITE);
                    graphics2D.drawRect(x, y, widthLogo, heightLogo);
                    graphics2D.dispose();
                    logo.flush();
                    image.flush();
                }
            }
        }catch (WriterException | IOException e){
            e.printStackTrace();
        }
        return image;
    }

    //将文件从文件中输出
    public static void showQRCode(BufferedImage image, OutputStream out) throws IOException {
        ImageIO.write(image, "JPEG", out);
    }
}
